// Word导出相关的组合式函数
import axios from 'axios'

export function useWordExport() {
    // 获取当前日期（格式：YYYY-MM-DD）
    const today = new Date();
    const formattedDate = today.toISOString().split('T')[0];

    // 导出Word - 试题版本
    const exportWordQuestions = async (examData, examTitle) => {
        if (!examData) {
            throw new Error('请先生成试卷');
        }

        try {
            // 在文件名末尾添加日期
            const filename = `${examTitle}_试题版_${formattedDate}.docx`;

            const response = await axios.post('/api/export_word', {
                data: JSON.stringify(examData),
                filename: filename,  // 使用带日期的文件名
                include_answers: false
            }, {responseType: 'blob'});

            downloadFile(response.data, filename);
        } catch (error) {
            throw new Error('导出失败，请稍后重试');
        }
    };

    // 导出Word - 带答案版本
    const exportWordWithAnswers = async (examData, examTitle) => {
        if (!examData) {
            throw new Error('请先生成试卷')
        }

        try {
            const filename = `${examTitle}_试题版_${formattedDate}.docx`;

            const response = await axios.post('/api/export_word', {
                data: JSON.stringify(examData),
                filename: filename,
                include_answers: true
            }, {responseType: 'blob'})

            downloadFile(response.data, filename)
        } catch (error) {
            throw new Error('导出失败，请稍后重试')
        }
    }

    // 下载文件的公共方法
    const downloadFile = (data, filename) => {
        const url = window.URL.createObjectURL(new Blob([data]))
        const link = document.createElement('a')
        link.href = url
        link.setAttribute('download', filename)
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)
    }

    return {
        exportWordQuestions,
        exportWordWithAnswers
    }
}